const express = require('express')
const bodyParser = require('body-parser')
const db = require('./module/db')
const md5 = require('md5')
const mongodb = require('mongodb')
const path = require('path')
const fs = require('fs')
const { upPic } = require('./module/upPic')
const { json, encode, decode } = require('./module/tools')
const app = express()
const formidable = require('formidable')
app.use(bodyParser.json())
app.use(express.static(__dirname + '/upload'))
app.use(express.static(path.resolve(__dirname, "../manage/dist")))
app.post("/login", function (req, res) {
    // adminName,passWord
    const { adminName, passWord } = req.body
    db.findOne('adminList', {
        adminName,
        passWord: md5(passWord + "*&|**&")
    }).then(async userInfo => {
        if (userInfo) {
            await db.insertOne('adminLog', {
                adminName,
                loginTime: Date.now()
            })
            res.json({
                ok: 1,
                msg: "成功",
                adminName,
                token: encode(adminName)
            })
        } else {
            json(res, -1, "网络连接错误")
        }
    })
})
// 获得店铺的所有类别
app.get("/allShopTypeList", async function (req, res) {
    db.find("shopTypeList", {
        sortObj: {
            createTime: -1
        }
    }).then(shopTypeList => {
        res.json({
            ok: 1,
            shopTypeList
        })
    })
})
/*******添加店铺******* */
app.post('/shopTypeList', function (req, res) {
    upPic(req, 'shopTypePic').then(({ ok, params, msg }) => {
        console.log(ok, params, msg);
        if (ok === 3) { // 成功
            db.insertOne('shopTypeList', {
                shopTypeName: params.shopTypeName,
                shopTypePic: params.shopTypePic,
                createTime: Date.now(),
                upTime: Date.now()
            }).then(data => {
                json(res, 1, '上传成功')
            }).catch(err => {
                json(res)
            })

        } else {
            json(res, -1, msg)
        }
    })
})

app.all('*', function (req, res, next) {
    // 解析token
    const { ok, info, msg } = decode(req.headers.authorization)
    // 判断是否解析正常，为1正常
    if (ok === 1) {
        next()
    } else {
        json(res, -2, msg);
    }
})
/*****************************店铺类别****************** */
app.get('/shopTypeList', async function (req, res) {
    let pageIndex = (req.query.pageIndex || 1) / 1 // 当前页数
    // let count = await db.count('shopTypeList'); // 统计总条数
    const whereObj = {}
    let shopTypeName = req.query.shopTypeName || ''
    if (shopTypeName.length > 0) {
        whereObj.shopTypeName = new RegExp(shopTypeName) //按名字进行模糊搜索
    }
    let count = await db.count('shopTypeList', whereObj)// 统计文档数量
    let limit = 5;
    let pageSum = Math.ceil(count / limit)
    if (pageSum < 1) {
        pageSum = 1
    }
    if (pageIndex > pageSum) {
        pageIndex = pageSum
    }
    if (pageIndex < 1) {
        pageIndex = 1
    }

    // console.log(req.headers.authorization);
    db.find('shopTypeList', {
        sortObj: {
            createTime: -1,
        },
        whereObj,
        limit,
        skip: (pageIndex - 1) * limit
    }).then(shopTypeList => {
        setTimeout(() => {
            res.json({
                ok: 1,
                shopTypeList,
                pageIndex,
                pageSum
            })
        }, 500)
    })
})

/*********************店铺类别删除*************** */
app.delete('/shopTypeList/:id', function (req, res) {
    const id = req.params.id
    // console.log(id);
    db.deleteOneById('shopTypeList', id)
        .then(() => {
            res.json({
                ok: 1,
                msg: '删除成功'
            })
        }).catch(() => {
            res.json({
                ok: -1,
                msg: '删除失败'
            })
        })
})

// 获得店铺的所有类别
app.get('./allShopTypeList', async function (req, res) {
    db.find('shopTypeList', {
        sortObj: {
            createTime: -1
        }
    }).then(shopTypeList => {
        res.json({
            ok: 1,
            shopTypeList
        })
    })
})
app.put("/shopTypeList", function (req, res) {
    upPic(req, "shopTypePic").then(async ({ ok, params, msg }) => {
        if (ok === 2) {// 格式 不正确
            json(res, -1, msg);
        } else {
            const $set = {
                shopTypeName: params.shopTypeName,
                upTime: Date.now()
            }
            // 判断如果上传图片，更新图片
            if (ok === 3) {
                $set.shopTypePic = params.shopTypePic;
            }
            // 可用
            await db.updateOneById("shopTypeList", params.shopTypeId, { $set });
            res.json({
                ok: 1,
                msg: "成功"
            })
        }
    })
})
/********************店铺************************ */
// 修改店铺
app.put("/shopList", function (req, res) {
    upPic(req, "shopPic").then(async ({ ok, params, msg }) => {
        if (ok === 2) {// 格式 不正确
            json(res, -1, msg);
        } else {
            console.log(ok, params);
            const info = await db.findOneById("shopTypeList", params.shopTypeId);
            const $set = {
                shopName: params.shopName,
                // shopPic:店铺图片
                shopTypeId: info._id,
                shopTypeName: info.shopTypeName,
                upTime: Date.now()
            }
            // 判断如果上传图片，更新图片
            if (ok === 3) {
                $set.shopPic = params.shopPic;
            }
            // 可用
            await db.updateOneById("shopList", params.shopId, { $set });
            res.json({
                ok: 1,
                msg: "成功"
            })
        }
    })
})
app.post("/shopList", function (req, res) {
    upPic(req, "shopPic").then(async ({ ok, msg, params }) => {
        if (ok === 3) {
            // 根据类别ID获得类别信息
            const info = await db.findOneById("shopTypeList", params.shopTypeId);
            params.createTime = params.upTime = Date.now();
            params.shopTypeId = info._id;
            params.shopTypeName = info.shopTypeName;
            console.log(params);
            await db.insertOne("shopList", params)
            json(res, 1, msg);
        }
        else json(res, -1, msg);
    })
})
app.get("/shopList", async function (req, res) {
    let pageIndex = (req.query.pageIndex || 1) / 1;// 当前页
    const whereObj = {};
    let shopName = req.query.shopName || "";
    if (shopName.length > 0) {
        whereObj.shopName = new RegExp(shopName);// 按照名字进行模糊搜索。
    }

    let count = await db.count("shopList", whereObj);// 统计文档数量
    let limit = 5;
    let pageSum = Math.ceil(count / limit);
    if (pageSum < 1) pageSum = 1;
    if (pageIndex > pageSum) pageIndex = pageSum;
    if (pageIndex < 1) pageIndex = 1;
    db.find("shopList", {
        sortObj: {
            createTime: -1
        },
        whereObj,
        limit,
        skip: (pageIndex - 1) * limit
    }).then(shopList => {
        // setTimeout(()=>{
        res.json({
            ok: 1,
            shopList,
            pageIndex,
            pageSum
        })
        // },2000)

    })
})
app.delete('/shopList/:id', function (req, res) {
    const id = req.params.id
    db.deleteOneById('shopList', id)
        .then(() => {
            res.json({
                ok: 1,
                msg: '删除成功'

            })

        }).catch(() => {
            res.json({
                ok: -1,
                msg: '删除失败'
            })
            console.log(111);
        })
})
// 根据店铺类别查找店铺列表
app.get('/shopList/:shopTypeId', async function (req, res) {
    const shopTypeId = mongodb.ObjectId(req.params.shopTypeId);
    const shopList = await db.find('shopList', {
        whereObj: {
            shopTypeId
        }, sortObj: {
            createTime: -1
        }
    })
    res.json({
        ok: 1,
        shopList
    })
})
/*******************商品相关接口************************ */
app.post('/goodsTypeList', async function (req, res) {
    console.log(req.body);
    // 根据店铺ID获得店铺详情
    const shopInfo = await db.findOneById('shopList', req.body.shopId)
    await db.insertOne('goodsTypeList', {
        goodsTypeName: req.body.goodsTypeName,
        createTime: Date.now(),
        shopId: shopInfo._id,
        shopName: shopInfo.shopName,
        shopTypeId: shopInfo.shopTypeId,
        shopTypeName: shopInfo.shopTypeName

    })
    res.json({
        ok: 1
    })
})
app.get("/goodsTypeList", async function (req, res) {
    let pageIndex = (req.query.pageIndex || 1) / 1;// 当前页
    const whereObj = {};
    let count = await db.count("goodsTypeList", whereObj);// 统计文档数量
    let limit = 5;
    let pageSum = Math.ceil(count / limit);
    if (pageSum < 1) pageSum = 1;
    if (pageIndex > pageSum) pageIndex = pageSum;
    if (pageIndex < 1) pageIndex = 1;
    db.find("goodsTypeList", {
        sortObj: {
            createTime: -1
        },
        whereObj,
        limit,
        skip: (pageIndex - 1) * limit
    }).then(goodsTypeList => {
        // setTimeout(()=>{
        res.json({
            ok: 1,
            goodsTypeList,
            pageIndex,
            pageSum
        })
        // },2000)

    })
})
app.delete('/goodsTypeList/:id', function (req, res) {
    const id = req.params.id
    db.deleteOneById('goodsTypeList', id)
        .then(() => {
            res.json({
                ok: 1,
                msg: '删除成功'

            })

        }).catch(() => {
            res.json({
                ok: -1,
                msg: '删除失败'
            })
            console.log(111);
        })
})

/*******************管理员************************** */
app.get('/adminLog', async function (req, res) {
    let pageIndex = (req.query.pageIndex || 1) / 1 // 当前页数
    let count = await db.count('adminLog'); // 统计总条数
    let limit = 5;
    let pageSum = Math.ceil(count / limit)
    if (pageSum < 1) {
        pageSum = 1
    }
    if (pageIndex > pageSum) {
        pageIndex = pageSum
    }
    if (pageIndex < 1) {
        pageIndex = 1
    }


    // console.log(req.headers.authorization);
    db.find('adminLog', {
        sortObj: {
            loginTime: -1,
        },
        limit,
        skip: (pageIndex - 1) * limit
    }).then(adminLog => {
        setTimeout(() => {
            res.json({
                ok: 1,
                adminLog,
                pageIndex,
                pageSum
            })
        }, 500)
    })
})
app.get("/adminList", async function (req, res) {
    let pageIndex = (req.query.pageIndex || 1) / 1;// 当前页
    const whereObj = {};
    let adminName = req.query.adminName || "";
    if (adminName.length > 0) {
        whereObj.adminName = new RegExp(adminName);// 按照名字进行模糊搜索。
    }

    let count = await db.count("adminList", whereObj);// 统计文档数量
    let limit = 5;
    let pageSum = Math.ceil(count / limit);
    if (pageSum < 1) pageSum = 1;
    if (pageIndex > pageSum) pageIndex = pageSum;
    if (pageIndex < 1) pageIndex = 1;
    db.find("adminList", {
        sortObj: {
            createTime: -1
        },
        whereObj,
        limit,
        skip: (pageIndex - 1) * limit
    }).then(adminList => {
        // setTimeout(()=>{
        res.json({
            ok: 1,
            adminList,
            pageIndex,
            pageSum
        })
        // },2000)

    })
})
app.delete('/adminLog/:id', function (req, res) {
    const id = req.params.id
    db.deleteOneById('adminLog', id)
        .then(() => {
            res.json({
                ok: 1,
                msg: '删除成功'
            })
        }).catch(() => {
            res.json({
                ok: -1,
                msg: '删除失败'
            })
        })
})

app.listen(80, function () {
    console.log('服务器开启成功');
})